package com.daoshu.socket.exception;

import com.daoshu.socket.bean.ErroCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 错误码处理类
 *
 * @author Allen
 */
@Slf4j
@Component
public class ErrorCodeHandler {

    private static final  Map<String, ErroCode> ERROR_CODE_MAP = new ConcurrentHashMap<>();

    public static ErroCode getErrorCode(String key) {
        log.debug("get error code by key {}", key);
        return ERROR_CODE_MAP.get(key);
    }

    public void loadErrorCode() {
        try {
            log.info("load server code message from messages-code.properties");
            Properties properties = PropertiesLoaderUtils.loadAllProperties("messages-code.properties");
            properties.forEach((key, pro) -> {
                String keyStr = String.valueOf(key);
                String proStr = String.valueOf(pro);
                ERROR_CODE_MAP.put(keyStr, new ErroCode(keyStr, proStr));
            });
            log.info("load default code message from messages-code-default.properties");
            Properties defaultProperties = PropertiesLoaderUtils.loadAllProperties("messages-code-default.properties");
            defaultProperties.forEach((key, pro) -> {
                String keyStr = String.valueOf(key);
                String proStr = String.valueOf(pro);
                ERROR_CODE_MAP.put(keyStr, new ErroCode(keyStr, proStr));
            });

        } catch (IOException e) {
            log.error("init load error from properties error", e);
        }
    }

}
